package com.hh.base.generator.model;

import com.hh.base.common.FiledBean;
import com.hh.base.common.TableBean;
import com.hh.base.util.StringUtil;

import java.util.List;

/**
 * Created by liuhanhui on 2017/10/27.
 */
public class DefaultModelGenerator extends ModelGenerator {

    private static String TEMPLATE_FIELD = "private {type} {name1};";

    private static String TEMPLATE_KEYS = "public static final String KEY_{name3} = \"{name0}\";";

    private static String TEMPLATE_METHOD_GET = "public {type} get{name2}() {\n\t\treturn this.get(\"{name0}\");\n\t}";
    private static String TEMPLATE_METHOD_SET = "public void set{name2}({type} {name1}) {\n\t\tthis.set(\"{name0}\", {name1});\n\t}";

    public String createModel(String template, TableBean tableBean) {
        template = template.replace("{modelname}", StringUtil.toUpperCase4Index(StringUtil.formatArgsName(tableBean.getName())) + "Model");
        template = template.replace("{tabelname}", tableBean.getName());

        List<FiledBean> filedBeanList = tableBean.getFiledBeanList();
        StringBuilder filedSB = new StringBuilder("");
        StringBuilder methodSB = new StringBuilder("");
        StringBuilder keySB = new StringBuilder("");
        for (FiledBean filedBean :
                filedBeanList) {
            String type = parseFieldType(filedBean.getType());
            String name0 = filedBean.getName();
            String name1 = StringUtil.formatArgsName(name0);
            String name2 = StringUtil.toUpperCase4Index(name1);
            String name3 = name0.toUpperCase();
            filedSB.append("\t//" + filedBean.getComment()).append("\n");
            String tempField = TEMPLATE_FIELD.replace("{type}", type).replace("{name1}", name1);
            filedSB.append("\t").append(tempField).append("\n\n");
            String tempMethodGet = TEMPLATE_METHOD_GET.replace("{type}", type).replace("{name2}", name2).replace("{name0}", name0);
            String tempMethodSet = TEMPLATE_METHOD_SET.replace("{type}", type).replace("{name2}", name2).replace("{name1}", name1).replace("{name0}", name0);
            methodSB.append("\t").append(tempMethodGet + "\n\n");
            methodSB.append("\t").append(tempMethodSet + "\n\n");

            keySB.append("\t").append(TEMPLATE_KEYS.replace("{name3}", name3).replace("{name0}", name0)).append("\n\n");

        }

        template = template.replace("{fileds}", filedSB.toString());
        template = template.replace("{gstter}", methodSB.toString());
        template = template.replace("{keys}",keySB.toString());
        return template;
    }

    private String parseFieldType(String type) {
        if ("int".equals(type)) {
            return "int";
        }

        if ("varchar".equals(type)) {
            return "String";
        }

        if ("datetime".equals(type)) {
            return "Date";
        }
        return type;
    }
}
